const mysql = require('mysql')

const pool  = mysql.createPool({
  connectionLimit : 10,
  host            : 'localhost',
  user            : 'root',
  password        : 'root',
  database        : 'books'
});

function getBooks() {
  return new Promise(function (resolve, reject) {
    // 查询数据
    pool.query('select * from book order by id desc', (err, res) => {
      if (err) {
        reject(err)
      } else {
        resolve(res)
      }
    })
  })
}

function delBook(id) {
  return new Promise(function (resolve, reject) {
    pool.query('delete from book where id = ?', id, (err, res) => {
      if (err) {
        reject(err)
      } else {
        resolve(res)
      }
    })
  })
}

function addBook(data) {
  return new Promise(function (resolve, reject) {
    pool.query('insert into book set ?', data, (err, res) => {
      if (err) {
        reject(err)
      } else {
        resolve(res)
      }
    })
  })
}

module.exports = {
  getBooks,
  delBook,
  addBook,
}
